# $Id:$
# Copyright (C) 2009  Thorsten Philipp

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


from Foundation import *
from AppKit import *

import objc
from objc import YES, NO, NULL
import sys, os, time

import Podcast


class atomatixDocument(NSDocument):
  

    chaptersview = objc.IBOutlet()
    podcastlogo = objc.IBOutlet()
    shownotes = objc.IBOutlet()
    chaptergraph = objc.IBOutlet()
    

    # =============
    # = Delegates =
    # =============
    def controlTextDidEndEditing_(self,aNotification):
      """Sets the save Status of the document to Dirty"""
      self.updateChangeCount_(NSChangeDone)

    
    # =======================
    # = Init Loading Saving =
    # =======================    
    def init(self):
      self = super(atomatixDocument, self).init()
      NSLog("Running init")
      self.soundavailable = NO # Some stuff is not possible unless we've loaded a audiofile (play,stop)
      
      
      self.chapters = NSMutableArray.arrayWithCapacity_(20)
      self.chapters.addObject_(NSMutableDictionary.alloc().init())
      self.podcast = NSMutableDictionary.alloc().init()
      self.podcast["genre"] = u"Podcast"
      self.episode = NSMutableDictionary.alloc().init()
      self.episode["number"] = 1
      self.audio = None
      self.podcastlogo = None
      self.genres = NSMutableArray.alloc().init()
      self.genres.append("Podcast")
      self.genres.append("Audiopodcast")
      
      return self
    
    
    def windowNibName(self):
      return u"atomatixDocument"
    
    def windowControllerDidLoadNib_(self, aController):
      super(atomatixDocument, self).windowControllerDidLoadNib_(aController)
      NSLog("Window Loaded")
      self.shownotes.setAlignment_(NSCenterTextAlignment)
      NSLog("Chaptergraph %s" % self.chaptergraph)
    
    def dataRepresentationOfType_(self,atype):
      """Will be called when User request to save. Returns NSData containing all necessary data"""
      tempdict = NSMutableDictionary.alloc().init()
      tempdict.setValue_forKey_(self.chapters,"chapters")
      tempdict.setValue_forKey_(self.podcast,"podcast")
      tempdict.setValue_forKey_(self.episode,"episode")
      tempdict.setValue_forKey_(self.audio,"audio")
      tempdict.setValue_forKey_(self.podcastlogo,"podcastlogo")
      NSLog("Saving: %s" % tempdict)
      return NSKeyedArchiver.archivedDataWithRootObject_(tempdict)
    
    def loadDataRepresentation_ofType_(self,data,atype):
      """Will be called when User wants to load a saved file. Returns YES or NO. (succesful?)"""
      NSLog("About to load data of type %s" % atype)
      dictionary = NSKeyedUnarchiver.unarchiveObjectWithData_(data)
      try:
        self.chapters = dictionary["chapters"]
      except:
        pass
      try:
        self.podcast = dictionary["podcast"]
      except:
        pass
      try:
        self.episode = dictionary["episode"]
      except:
        pass
      try:
        self.audio = dictionary["audio"]
        self.soundavailable = YES
      except:
        pass
      try:
        self.podcastlogo = dictionary["podcastlogo"]
      except:
        pass
      return True
      

    # ===========
    # = Episode =
    # ===========
    @objc.IBAction
    def inrecmentEpisodeNumber_(self,sender):
      """Increments self.episode.number"""
      self.episode["number"] += 1
      NSLog("Episodenumber is now %s" % self.episode["number"])
    
    @objc.IBAction
    def decrementEpisodeNumber_(self,sender):
      """Decrements self.episode.number"""
      self.episode["number"] -= 1
      if self.episode["number"] <= 0:
        self.episode["number"] = 1
        
    # ===========
    # = Podcast =
    # ===========
    @objc.IBAction
    def setPodcastGenre_(self,sender):
      """docstring for setPodcastGenre_"""
      
      self.podcast["genre"] = sender.titleOfSelectedItem()

    # ============
    # = Chapters =
    # ============
    @objc.IBAction
    def selectedTableRow_(self,sender):
      """Currently selected Chapter ID"""
      self.selected_row = sender.selectedRow()
      self.currentoffset = self.chapters[self.selected_row]['chapterOffset']
      NSLog("Set Offset to %s" % self.currentoffset)

    @objc.IBAction
    def addChapter_(self,sender):
      """Create a new empty chapter in chapters table view"""
      self.chapter = NSMutableDictionary.alloc().init()
      self.chapter.setValue_forKey_(1,"chapterOffset")
      self.chapters.addObject_(self.chapter)
      self.chapter.release()
      self.chaptersview.rearrangeObjects()

    @objc.IBAction  
    def removeChapter_(self,sender):
      """Remove the currently selected Chapter"""
      if(self.selected_row >= 0):
        self.chapters.removeObjectAtIndex_(self.selected_row)
        self.chaptersview.rearrangeObjects()
    
    @objc.IBAction
    def play_(self,sender):
      """Play self.audio"""
      NSLog("Playing")
      self.audio.setCurrentTime_(float(self.currentoffset/1000))
      self.audio.play()
      self.audio.resume()

    @objc.IBAction
    def pause_(self,sender):
      """Pause self.audio"""
      self.audio.pause()


    # ===================================
    # = Import / Export
    # ===================================

    @objc.IBAction
    def exportEpisodexml_(self,sender):
        podcastname = self.podcastname.stringValue()

        NSLog(u"podcastname: %s" % podcastname)
        NSLog(u"episodenu: %s" % self.episodenumber.stringValue())
        filename = "/Users/thorstenphilipp/Desktop/test.png"
        pngfile = open(filename,"w")
        pngfile.write(self.getPNGFromNSImage(self.podcastlogo))
        pngfile.close()


        NSLog("self.chapters %s" % self.chapters)
        NSLog("chapters: %s" % automatixController.chapters )
        # tiff.writeToFile_(filename)

    @objc.IBAction    
    def openPodcast_(self, sender):
      """Display a file select dialog and import atoms from that podcast"""
      panel = NSOpenPanel.openPanel()
      panel.setCanChooseDirectories_(NO)
      panel.setAllowsMultipleSelection_(NO)
      panel.setTitle_("Select Podcast File ...")
      filetypes = ('mp4','m4a', 'm4p')
      ret_value = panel.runModalForTypes_(filetypes)
      if ret_value:
        NSLog("Will open Soundfile: %s" % panel.filenames()[0])
        self.audio = NSSound.alloc().initWithContentsOfFile_byReference_(panel.filenames()[0],NO)
        self.soundavailable = YES
        
    
    # ===========
    # = Utility =
    # ===========
    def getPNGFromNSImage(self,nsimage):
        representations = nsimage.representations()
        nsimage.setSize_([6000,6000])

        return nsimage.representations()[0].representationUsingType_properties_(NSPNGFileType,
            {}).bytes()  

    def buildNSImage(self,filename):
        NSLog("Building NSImage")
        return NSImage.alloc().initWithContentsOfFile_(filename)
        
        
    
class TPDurationFormatter(NSFormatter):
  """Converting Time Offsets between integer representation (milliseconds) and human readable string"""
  
  def stringForObjectValue_(self,anObject):
    """convert the cell's object to a string"""
    NSLog("stringForObjectValue %s" % anObject)
    if anObject == None:
      return("00:00:00.000")
    seconds = anObject/1000
    milliseconds = anObject % 1000
    timestamp = "%s.%d" % (time.strftime("%H:%M:%S",time.gmtime(int(seconds))),milliseconds)
    return(timestamp)

  def getObjectValue_forString_errorDescription_(self,string):
    """method you convert the string to the object associated with the cell."""
    timestr = "00:00:00"
    milli = second = minute = hour = 0
    try:
      (timestr,milli) = string.split('.')
    except:
      timestr = string
    try:
      NSLog("Time: %s" % time)
      (year,month,day,hour,minute,second,wday,yday,isdst) = time.strptime(timestr, "%H:%M:%S")
      NSLog("Matching")
    except:
      NSLog("NotMatching")
    try:
      milli = int(milli)
    except:
      milli = 0
    anObject = ((second+(minute*60)+(hour*60*60))*1000)+milli
    NSLog("anObject: %s" % anObject)
    error = None
    return(YES,anObject,error)

  def attributedStringForObjectValue_withDefaultAttributes_(self,anObject,attributes):
    """n the third method, attributedStringForObjectValue:withDefaultAttributes:, you convert the object to a string that has attributes associated with it. For example, if you want negative financial amounts to appear in red, you have this method return a string with an attribute of red text. In"""
    pass
    